<template>
	<view>
		<tab @change="onTypeChange" />
		<view style="height: 1rpx;width: 100%;background: #EEEEEE;"></view>
		<mescroll-body ref="mescroll" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption"
			:up="upOption">
			<block v-for="(item, index) in signcentlist" :key="index">
				<list-item :item="item" @reset="reloadList"></list-item>
				<view class="column-css view-cente" style="border-bottom: 3rpx solid #EEEEEE;padding:20rpx 10rpx;display: none;">
					<view class="row-css" style="justify-content: space-between;font-weight: bold;">
						<view>《{{ item.contractName }}》</view>
						<view v-if="item.state != 2">{{ item.state == 1 ? '生效中' : item.state == 3 ? '已签约' : '已作废' }}
						</view>
					</view>
					<view style="padding: 15rpx 0;">合同编号：{{ item.contractNo }} | {{ item.plateNum }}</view>
					<view class="row-css" style="justify-content: space-between;">
						<view style="padding: 5rpx 0;word-break: break-all;white-space: pre-wrap;">
							合同有效期:{{ item.validPeriod }}</view>
					</view>

					<!-- 测试时打开，有电子合同签字段暂时字段没有加上；发布时放开判断 -->
					<!-- 新增电子合同签约功能  isSign为1表示为有电子单反之则没有 -->
					<view  v-if="isWeixin == true">
						<view class="row-css" style="justify-content:flex-end;padding: 16rpx 0rpx;" v-if="item.isSign == 0">
						<!-- <view class="row-css" style="justify-content:flex-end;padding: 16rpx 0rpx;"> -->
							<view class="row-css view-border-radius" @click="onSigning(item)">电子合同签约</view>
							<view class="row-css view-border-radius" @click="onDetail(item)">查看详情</view>
						</view>
						<view class="row-css" style="justify-content:flex-end;padding: 16rpx 0rpx;" v-else>
							<view class="row-css view-border-radius" @click="onSignature(item)">查看详情</view>
						</view>
					</view>
					<view v-else>
						<view class="row-css" style="justify-content:flex-end;padding: 16rpx 0rpx;">
							<!-- <view class="row-css view-border-radius" @click="onSigning(item)">电子合同签约</view> -->
							<view class="row-css view-border-radius" @click="onDetail(item)">查看详情</view>
						</view>
					</view>
					
				</view>

			</block>
		</mescroll-body>
		<!-- <view v-if="!issign" class="column-css" style="position: fixed;bottom: 0;width: 100%; background: #FFFFFF;">
			<view class="view-deltorder" style="margin: 30rpx;border: 1rpx solid #007AFF;" @click="onReadysign()">开始签约</view>
		</view> -->
		<uni-popup ref="popup" type="center">
			<view class="column-css"
				style="background: #FFFFFF;width: 630rpx;border-radius: 10rpx;align-items: center;padding: 15rpx 0;">
				<view style="padding: 10rpx;margin-bottom: 10rpx;font-size: 36rpx;">
					您即将签署
					<text style="font-size: 32rpx;" @click="opensign()">《车辆货物运输协议》</text>
				</view>
				<view class="column-css" style="padding: 0 20rpx; text-align: center;font-weight: 100;">
					您已进入
					<text style="color: #007AFF;">【{{ signedInfo.platformCoName }}】</text>
					签约流程，请认真核对签约信息
				</view>
				<view style="width: 100%; height: 1rpx;background: #B9B9B9;margin-top: 10rpx;"></view>
				<view style="margin:0 10rpx;margin-top: 10rpx;padding: 20rpx 0;">
					<view>网络承运商信息：{{ signedInfo.platformCoName }}</view>
					<view class="column-css" style="margin-top: 20rpx;">
						<view style="padding: 10rpx;">
							签约姓名：{{ signedInfo.driverName }}
							<image style="width: 120rpx;height: 35rpx;" mode="aspectFill"
								src="../../static/icon_verifled.png"></image>
						</view>
						<view style="padding: 10rpx;">签约车牌号：{{ signedInfo.plateNum }}</view>
						<view style="padding: 10rpx;">车辆登记有效期：{{ signedInfo.validPeriod }}</view>
						<view style="padding: 10rpx;">随车手机号：{{ signedInfo.mobile }}</view>
					</view>
				</view>
				<view style="width: 100%;height: 1rpx;background: #B9B9B9;"></view>
				<view class="row-css" style="width: 100%;">
					<view class="row-css" style="width: 49%;justify-content: center; padding: 20rpx; color: #B9B9B9;"
						@click="signcanal()">关闭</view>
					<view style="height: auto;width: 1rpx;background: #B9B9B9;"></view>
					<view class="row-css" style="width: 49%;justify-content: center; padding: 20rpx;color: #007AFF;"
						@click="signContract()">预览合同</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
	import MescrollBody from '@/uni_modules/mescroll-uni/components/mescroll-body/mescroll-body.vue';

	import permision from "@/js_sdk/wa-permission/permission.js"
	import Tab from "./components/sign/tab.vue"
	import ListItem from "./components/sign/list-item.vue"
	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			MescrollBody,
			Tab,
			ListItem
		},
		data() {
			return {
				signcentlist: [],
				orderSignList: [],
				signedInfo: {},
				issign: false,
				page: 1,
				pageSize: 10,
				mescroll: null, // mescroll实例对象 (此行可删,mixins已默认)
				// 下拉刷新的配置(可选, 绝大部分情况无需配置)
				downOption: {},
				// 上拉加载的配置(可选, 绝大部分情况无需配置)
				upOption: {
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: '暂无相关数据'
					}
				},
				isShow: false,
				//#ifdef MP-WEIXIN
				isWeixin:true,
				//#endif
				
				signType: "1"
			};
		},
		methods: {
			onTypeChange(type) {
				this.signType = type
				this.mescroll.resetUpScroll();
			},
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调*/
			downCallback(mescroll) {
				mescroll.resetUpScroll(); // 重置列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
			},
			/*上拉加载的回调*/
			upCallback(mescroll) {
				this.page = mescroll.num; // 页码, 默认从1开始
				//联网加载数据
				this.onwaybill(mescroll);
			},
			reloadList() {
				this.mescroll.resetUpScroll()
			},
			//查看合同详情
			onDetail: function(item) {
				uni.showLoading({
					title: '合同信息加载中。。。',
					mask: true
				});
				//上传、下载
				uni.downloadFile({
					url: item.contractUrl,
					// #ifdef MP-WEIXIN
					filePath: wx.env.USER_DATA_PATH + '/' + item.contractName +
						'.pdf', //指定的本地文件路径   一定要带文件后缀名  不然无法打开   wx.env.USER_DATA_PATH类似本地文件根目录
					// #endif
					success(res) {
						let data = '';
						// #ifdef MP-WEIXIN
						data = res.filePath;
						// #endif
						// #ifdef APP-PLUS
						data = res.tempFilePath;
						// #endif
						uni.openDocument({
							filePath: data,
							showMenu: true, //表示右上角是否有转发按钮
							fileType: 'pdf',
							success: function(res) {
								uni.hideLoading();
								console.log('打开文档成功');
							}
						});
					}
				});
			},
			// 查看电子签详情
			onSignature(item) {
				uni.showLoading({
					title: '合同信息加载中。。。',
					mask: true
				});
				this.wxRequest({
					url: `${this.API1}/seal/driverNotify/getBillNoSignUrl`,
					method: 'POST',
					data: {
						loadingBillNo: item.contractNo
					},
					title: '加载中...',
					success: function(res) {
						var data = res.data.data
						if (res.data.code == 0) {
							//上传、下载
							uni.downloadFile({
								url: data, //下载资源的url
								success: function(res) {
									const filePath = res
									.tempFilePath; //tempFilePath临时文件路径，下载后的文件会存储到一个临时文件
									//新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
									uni.openDocument({
										filePath: filePath, //文件路径，可通过 downFile 获得
										showMenu: true, //表示右上角是否有转发按钮
										fileType: 'pdf', //文件类型，指定文件类型打开文件，有效值 doc, xls, ppt, pdf, docx, xlsx, pptx，支付宝小程序仅支持pdf
										success: function(res) {
											uni.hideLoading();
											console.log('打开文档成功');
										}
									});
								}
							});
						}

					}
				})
			},
			onwaybill(mescroll) {
				this.wxRequest({
					url: `${this.API}/driverYearSign/signList`,
					method: 'POST',
					data: {
						driverId: uni.getStorageSync(this.DATA_KEY.userInfo).driverId,
						pageNum: this.page,
						pageSize: this.pageSize,
						signType: this.signType
					},
					title: '加载中...',
					success: res => {
						this.orderSignList = res.data.data.signList;

						if (this.page == 1) {
							// console.log('555 ', this.signcentlist);
							this.signcentlist = [];
							// console.log('shi10 ', this.signcentlist);
							if (res.data.data.signList.length > 0) {
								this.signcentlist = res.data.data.signList;
							}
							// console.log('shi11 ', this.signcentlist);
						}
						if (res.data.data.orderSignList.list.length > 0) {
							this.signcentlist.push.apply(this.signcentlist, res.data.data.orderSignList.list);
						}
						if (mescroll != null) {
							mescroll.endBySize(this.signcentlist.length - 1, res.data.data.orderSignList
								.total);
							setTimeout(() => {
								this.mescroll.endSuccess(this.signcentlist.length);
							}, 20);
						}
						for (var i = 0; i < this.orderSignList.length; i++) {
							if (this.orderSignList[i].state == 1) {
								this.issign = true;
							}
						}
						// console.log('sh22i ', this.signcentlist);
					}
				});
			},
			onReadysign() {
				this.$refs.popup.open('center');
			},
			signcanal() {
				this.$refs.popup.close();
			},
			signContract() {
				uni.navigateTo({
					url: '../personal/annualvisa?platformCoNo=' + this.signedInfo.platformCoNo
				});
				this.$refs.popup.close();
			},
			// 电子合同签约
			onSigning(item) {
				uni.setStorageSync('loadingBillNo', item.contractNo);
				var that = this
                var livingBodyState =uni.getStorageSync(that.DATA_KEY.userInfo).livingBodyState
				if(livingBodyState == 1){
					that.wxRequest({
						url: `${this.API1}/seal/driverNotify/authSign`,
						method: 'POST',
						data: {
							mobile: uni.getStorageSync(that.DATA_KEY.userInfo).mobile,
							driverId: uni.getStorageSync(that.DATA_KEY.userInfo).driverId,
							"authType": "1",
							//#ifdef MP-WEIXIN
							redirectUrl:""
							//#endif
							//#ifdef APP-PLUS
							// redirectUrl:"y2t://app/realBack"
							redirectUrl:"https://static-mp-3f064dc3-6a80-42a4-a5e3-0aafc4682c3a.next.bspapp.com/#/"
							//#endif
						},
						title: '加载中...',
						success: function(res) {
							console.log(res.data, '111111111111')
							let url = ""
							//#ifdef MP-WEIXIN
							url = res.data.data
							//#endif
							// #ifdef APP-PLUS
							url = res.data.data
							// #endif
							///seal/driverNotify/authSign  判断用户是否认证  code = 0未认证，1已认证
							if (res.data.code == 0) {
								uni.showModal({
									title: '提示',
									content: '您尚未完成E签宝平台个人身份认证，请完成认证后继续签约',
									confirmText: '去认证',
									success: function(res) {
										if (res.confirm) {
											// #ifdef APP-PLUS
											switch (uni.getSystemInfoSync().platform) {
												case 'android':
													permision.requestAndroidPermission(
														"android.permission.RECORD_AUDIO")
													permision.requestAndroidPermission(
														"android.permission.CAMERA").then((e) => {
													if (e === -1) {
														uni.showToast({
															title: "您已经永久拒绝摄像头权限，请在应用设置中手动开启",
															icon: "none"
														})
													} else if (e === 0) {
														uni.showToast({
															title: "您拒绝了摄像头授权",
															icon: "none"
														})
													} else if (e === 1) {
														
														uni.navigateTo({
															url: '/pages/personal/webview?url=' +encodeURIComponent(url)
														})
													} else {
														uni.showToast({
															title: "授权返回值",
															icon: "none"
														})
													}
												})
													break;
												case 'ios':
													permision.judgeIosPermission("record")
													permision.judgeIosPermission("camera").then((e) => {
													if (e === -1) {
														uni.showToast({
															title: "您已经永久拒绝摄像头权限，请在应用设置中手动开启",
															icon: "none"
														})
													} else if (e === 0) {
														uni.showToast({
															title: "您拒绝了摄像头授权",
															icon: "none"
														})
													} else if (e === 1) {
														uni.navigateTo({
															url: '/pages/personal/webview?url=' +encodeURIComponent(url)
														})
													} else {
														uni.showToast({
															title: "授权返回值",
															icon: "none"
														})
													}
												})
												break;
								}
											// #endif
					
											// #ifdef MP-WEIXIN
											uni.navigateTo({
												url: '/pages/personal/webview?url=' +
													encodeURIComponent(url)
											})
											
											// #endif
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
							} else if (res.data.code == 1) {
								//已实名认证后，调取签署接口生成链接跳转到链接地址签署合同
								that.wxRequest({
									url: `${that.API1}/seal/driverNotify/fileSign`,
									method: 'POST',
									data: {
										mobile: uni.getStorageSync(that.DATA_KEY.userInfo).mobile,
										driverId: uni.getStorageSync(that.DATA_KEY.userInfo).driverId,
										loadingBillNo: item.contractNo,
										loadingOrderId: null,
										"type":"1",
										"authType":"1",
										//#ifdef MP-WEIXIN
										redirectUrl:""
										//#endif
										//#ifdef APP-PLUS
										// redirectUrl:"y2t://app/realBack"
										redirectUrl:"https://static-mp-3f064dc3-6a80-42a4-a5e3-0aafc4682c3a.next.bspapp.com/#/"
										//#endif
									},
									title: '加载中...',
									success: function(res) {
										console.log(res,11111)
										let urls = ""
										//#ifdef MP-WEIXIN
										urls = res.data.data
										//#endif
										//#ifdef APP-PLUS
										urls = res.data.data
										// #endif
										// #ifdef APP-PLUS
										switch (uni.getSystemInfoSync().platform) {
											case 'android':
												permision.requestAndroidPermission(
													"android.permission.RECORD_AUDIO")
												permision.requestAndroidPermission(
													"android.permission.CAMERA").then((e) => {
													if (e === -1) {
														uni.showToast({
															title: "您已经永久拒绝摄像头权限，请在应用设置中手动开启",
															icon: "none"
														})
													} else if (e === 0) {
														uni.showToast({
															title: "您拒绝了摄像头授权",
															icon: "none"
														})
													} else if (e === 1) {
														
														uni.navigateTo({
															url: '/pages/personal/webview?url=' +encodeURIComponent(urls)
														})
													} else {
														uni.showToast({
															title: "授权返回值",
															icon: "none"
														})
													}
												})
												break;
											case 'ios':
												permision.judgeIosPermission("record")
												permision.judgeIosPermission("camera").then((e) => {
													if (e === -1) {
														uni.showToast({
															title: "您已经永久拒绝摄像头权限，请在应用设置中手动开启",
															icon: "none"
														})
													} else if (e === 0) {
														uni.showToast({
															title: "您拒绝了摄像头授权",
															icon: "none"
														})
													} else if (e === 1) {
														uni.navigateTo({
															url: '/pages/personal/webview?url=' +encodeURIComponent(urls)
														})
													} else {
														uni.showToast({
															title: "授权返回值",
															icon: "none"
														})
													}
												})
												break;
										
										}
										
										// #endif
										// #ifdef MP-WEIXIN
										uni.navigateTo({
											url: '/pages/middle/bizpage?url=' +encodeURIComponent(urls)
										})
										// #endiff
					
									}
								})
							}
						},
						fail(err) {
							console.log(err)
						}
					})
				}else{
					uni.showModal({
						title: '提示',
						content: '您尚未完成E签宝平台个人身份认证，请完成认证后继续签约',
						confirmText: '去认证',
						success: function(res) {
							if (res.confirm) {
								let that = this;
								that.wxRequest({
									url: `${that.API}/driverService/getDriverIdCardInfo`,
									method: 'POST',
									data: {
										driverId: that.user.driverId,
										platformCoNo: uni.getStorageSync(that.DATA_KEY.platformCoNo)
									},
									title: '加载中...',
									success: res => {
										let accessToken = res.data.data.accessToken; //认证令牌
										that.accessToken = accessToken
										let taxNumber = res.data.data.taxNumber; //平台税号
										let realName = res.data.data.driverName;
										let idCard = res.data.data.idcard;
										let idPhotoUp = res.data.data.idcard1Base64;
										let idPhotoDown = res.data.data.idcard2Base64;
										that.wxRequestData({
											url: `${that.API2}/api/face/getFaceQRCode?access_token=` + accessToken,
											method: 'POST',
											title: '加载中...',
											data: {
												companyTaxNumber: taxNumber,
												realName: realName,
												idCard: idCard,
												idPhotoUp: idPhotoUp,
												idPhotoDown: idPhotoDown,
												callbackUrl: `${that.API}/driverService/isLivingBodyState`
											},
											success: res => {
												console.log("===================>2",res);
												if (res.data.code == 0) {
													let orderNumber = res.data.data.orderNumber;
													that.orderNumber = orderNumber
													that.wxRequest({
														url: `${that.API}/driverService/saveFaceVerifyOrderNumber`,
														method: 'POST',
														data: {
															driverId: that.user.driverId,
															orderNumber: orderNumber,
															platformCoId: uni.getStorageSync(that.DATA_KEY.platformCoNo) == '0001' ? '100001' : '100002'
														},
														success: res => {
															// #ifdef APP-PLUS
															uni.showModal({
																title: '提示',
																content: '是否去进行实名认证?跳转进行实名认证后需要重新打开当前APP!',
																success: function(res) {
																	if (res.confirm) {
																		console.log('用户点击确定');
																		that.timer = null
																		that.flag = true
																		plus.share.getServices(
																			function(res) {
																				var sweixin = null;
																				console.log(res);
																				for (var i = 0; i < res.length; i++) {
																					var t = res[i];
																					console.log(t);
																					if (t.id == 'weixin') {
																						sweixin = t;
																					}
																				}
																				if (sweixin) {
																					console.log('dddd=', 'a=' + sweixin + '=b');
																					sweixin.launchMiniProgram({
																						// id: 'gh_cec8224b00da',
																						id: 'gh_45eec401ff1c',
																						type: 0, //0-正式版 1.测试版，2，体验版
																						path: 'pages/verify/info/index?id=' + orderNumber
																					});
																				}
																			},
																			function(res) {
																				console.log(JSON.stringify(res));
																			}
																		);
																	} else if (res.cancel) {
																		console.log('用户点击取消');
																		that.timer = null
																	}
																}
															});
															// #endif
															
															// #ifdef MP-WEIXIN
															uni.showModal({
																title: '提示',
																content: '是否去进行实名认证?',
																success: function(res) {
																	if (res.confirm) {
																		that.timer = null
																		console.log(that.timer)
																		
																		that.flag = true
																		console.log('用户点击确定');
																		uni.navigateToMiniProgram({
																			// appId: 'wxfd2861dc1c86b3a0',
																			appId: 'wxfc1e27e05fdd062b',
																			// path: 'pages/verify/info/index?id=' + orderNumber,
																			path: 'pages/verify/info/index?id=' + orderNumber,
																			envVersion: 'release',
																			success(res) {
																				console.log('跳转成功');
																			},
																			fail(res) {
																				console.log('跳转失败' + JSON.stringify(res));
																			}
																		});
																	} else if (res.cancel) {
																		that.timer = null
																		console.log(that.timer)
																		console.log('用户点击取消');
																	}
																}
															});
															// #endif
														}
													});
												}
											}
										});
									}
								});
							}else if (res.cancel) {
							console.log('用户点击取消');
							}
	
				},
				// }
	          })
			}
			}
		},
		onShow() {
			this.onwaybill(null);

		},
		onLoad() {
			// this.onwaybill(null);
			// this.wxRequest({
			// 	url: `${this.API}/driverYearSign/toBeSignedInfo`,
			// 	method: 'POST',
			// 	data: {
			// 		driverId: uni.getStorageSync(this.DATA_KEY.userInfo).driverId,
			// 		etpId: uni.getStorageSync(this.DATA_KEY.etpId)
			// 	},
			// 	title: '加载中...',
			// 	success: res => {
			// 		this.signedInfo = res.data.data;
			// 	}
			// });
		}
	};
</script>

<style lang="scss" scoped>
	.row-css {
		display: flex;
		flex-direction: row;
	}

	.column-css {
		display: flex;
		flex-direction: column;
	}

	.view-cente {
		background: #ffffff;
		padding: 0 30rpx;
		margin: 20rpx;
		border-radius: 15rpx;
	}

	.view-border-radius {
		/* width: 120rpx; */
		height: 40rpx;
		line-height: 40rpx;
		white-space: nowrap;
		padding: 5rpx 15rpx;
		border-radius: 15rpx;
		border: 1rpx solid #2979ff;
		color: #2979ff;
		margin: 0rpx 8rpx;
	}

	.view-deltorder {
		text-align: center;
		margin: 10rpx 60rpx;
		padding: 15rpx 0;
		color: #007aff;
		border-radius: 8rpx;
	}
	.tab-bar {
		display: flex;
		align-items: center;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 99;
		.tab-bar-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #fff;
			color: #999;
			padding: 20rpx 0;
			border: 2rpx solid #999;
			&.active {
				background-color: #007aff;
				color: #fff;
				border: 2rpx solid #007aff;
			}
		}
	}
	.tab-bar-height {
		height: 80rpx;
	}
</style>
